﻿using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

//////////////////////////////////////////////////////////////////////////
//Advisor_Template.aspx.cs                                              //
//Last Edited: 23 Mar 2012                                              //
//                                                                      //
//This file contains the template functionality available to advisors.  //
//////////////////////////////////////////////////////////////////////////
public partial class Advisor_Template : System.Web.UI.Page
{
    //Instance Variables for graphical view
    List<Course> courseList = new List<Course>();
    List<Elective> electiveList = new List<Elective>();

    /// <summary>
    /// Page_Load() 
    /// 
    /// Ininitializes the page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        //If this is the first time we load the page
        if (!IsPostBack)
        {
            //Populate the YearList for adding courses to be for 10 years (0001-0010)
            for (int i = 1; i < 10; i++)
            {
                YearList.Items.Add(new ListItem("000" + i));
            }
            YearList.Items.Add(new ListItem("0010"));
            //Populate the create elective year list for adding courses to be for 10 years (0001-0010)
            for (int i = 1; i < 10; i++)
            {
                ElectiveYearList.Items.Add(new ListItem("000" + i));
            }
            ElectiveYearList.Items.Add(new ListItem("0010"));
            //Populate the add elective year list for adding courses to be for 10 years (0001-0010)
            for (int i = 1; i < 10; i++)
            {
                AddElectiveYearList.Items.Add(new ListItem("000" + i));
            }
            AddElectiveYearList.Items.Add(new ListItem("0010"));
            //Populate the MoveYearList for listview to be 10 years (0001-0010)
            for (int i = 1; i < 10; i++)
            {
                MoveYearList.Items.Add(new ListItem("000" + i));
            }
            MoveYearList.Items.Add(new ListItem("0010"));
            //Ininitialize the templateID session variable
            String templateID = Request.QueryString["id"];
            Session["Advisor_templateID"] = templateID;
            Session["Advisor_templateYearGV"] = "1";
            //Get the http string value to determine which page to display
            String value = Request.QueryString["view"];
            if (value == null) value = "editTemplate";
            if (value.Equals("editTemplate"))
            {
                //Change state of elements
                //Keep page in Choose Template View
                colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
                //borderStyle.Text = "";
                HeaderText.Text = "Choose Template to Edit";
                setEverything(false, false, false, false, false, true, false, false, true);
                //populate template list
                List<Dictionary<String, Object>> templates = StoredProcedures.getTemplates();
                foreach (Dictionary<String, Object> i in templates)
                {
                    TemplateList.Items.Add(new ListItem(i["name"].ToString(), i["templateID"].ToString()));
                }
                if (templateID != null)
                {
                    foreach (ListItem i in TemplateList.Items)
                    {
                        if (i.Value.Equals(templateID))
                        {
                            int index = TemplateList.Items.IndexOf(i);
                            TemplateList.SelectedIndex = index;
                            ViewTemplateButton_Click(sender, e);
                            if (ViewRadio.SelectedIndex == 0)
                            {
                                //Graphical View
                                colorStyle.Text = "";
                                //borderStyle.Text = "";
                                setEverything(false, false, true, false, false, false, true, false, true);
                                initializeJavaScript();
                            }
                            else
                            {
                                //List View
                                colorStyle.Text = "";
                                //borderStyle.Text = "";
                                setEverything(false, false, false, true, false, false, true, false, true);
                                generateListViewTable();
                            }
                            break;
                        }
                    }
                }
            }
            else //if (value.Equals("createTemplate"))
            {
                //Set elements appropriately and initialize session variables for saving, modifying, and deleting courses and electives
                HeaderText.Text = "New Template";
                AddCourse.Enabled = true;
                AddElective.Enabled = true;
                TemplateInfoBox.Visible = true;
                TemplateName.Text = "Default Template Name";
                if (ViewRadio.SelectedIndex == 0)
                {
                    //Graphical View
                    colorStyle.Text = "";
                    //borderStyle.Text = "";
                    setEverything(false, false, true, false, false, false, true, false, true);
                    initializeJavaScript();
                }
                else
                {
                    //List View
                    colorStyle.Text = "";
                    //borderStyle.Text = "";
                    setEverything(false, false, false, true, false, false, true, false, true);
                    generateListViewTable();
                }
            }
        }
        else // the page had a post-back
        {
            TemplateInfoBox.Visible = true;
            TemplateName.Enabled = true;
            if (ViewRadio.SelectedIndex == 0)
            {
                initializeJavaScript();
                //Graphical View
                colorStyle.Text = "";
                setEverything(false, false, true, false, false, false, true, false, true);
            }
            else
            {
                generateListViewTable();
                //List View
                colorStyle.Text = "";
                setEverything(false, false, false, true, false, false, true, false, true);
            }
        }
    }
    /// <summary>
    /// ChangeDisplayedSemesterHelper()
    /// 
    /// Changes the semester to only display Fall when the first year is selected in a template for a course move
    /// or course/elective addition to the template
    /// </summary>
    /// <param name="MoveYearList">The move year list to manipulate</param>
    /// <param name="MoveSemesterList">The move semester list to manipulate</param>
    private void ChangeDisplayedSemesterHelper(DropDownList MoveYearList, DropDownList MoveSemesterList)
    {
        if (MoveYearList.SelectedItem == null)
            return;
        int selectedSemesterIndex = MoveSemesterList.SelectedIndex;
        int intStartYear = 1;
        int moveYear = Convert.ToInt32(MoveYearList.SelectedItem.Text);
        if (moveYear == intStartYear)
        {
            MoveSemesterList.Items.Clear();
            MoveSemesterList.Items.Add(new ListItem("Fall"));
        }
        else
        {
            MoveSemesterList.Items.Clear();
            MoveSemesterList.Items.Add(new ListItem("Fall"));
            MoveSemesterList.Items.Add(new ListItem("Spring"));
            MoveSemesterList.Items.Add(new ListItem("Summer"));
            MoveSemesterList.SelectedIndex = selectedSemesterIndex;
        }
    } // end ChangeDisplayedSemesterHelper()

    /// <summary>
    /// MoveCourseChangeDisplayedSemester()
    /// 
    /// Updates all the semester lists on the page to reflect the appropriate semester to display (depending on start date)
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void MoveCourseChangeDisplayedSemester(object sender, EventArgs e)
    {
        ChangeDisplayedSemesterHelper(MoveYearList, MoveCourseList);
    } // end MoveCourseChangeDisplayedSemester()
    /// <summary>
    /// AddCourseChangeDisplayedSemester()
    /// 
    /// Updates all the semester lists on the page to reflect the appropriate semester to display (depending on start date)
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddCourseChangeDisplayedSemester(object sender, EventArgs e)
    {
        //Get add course page elements set
        //Change Content
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add A Course To Template";
        //Change State of elements
        CancelButton.Text = "Cancel";
        setEverything(true, false, false, false, false, false, false, true, false);
        ChangeDisplayedSemesterHelper(YearList, SemesterList);
    } //ends AddCourseChangeDisplayedSemester()

    /// <summary>
    /// CreateElectiveChangeDisplayedSemester()
    /// 
    /// Updates all the semester lists on the page to reflect the appropriate semester to display (depending on start date)
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void CreateElectiveChangeDisplayedSemester(object sender, EventArgs e)
    {
        //Change state of elements
        //Keep in Add Elective view
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        //borderStyle.Text = "<style>.boxBorder {border-bottom:2px solid #000000;}</style>";
        HeaderText.Text = "Add An Elective To Template";
        if (ElectiveSubjectList.SelectedItem != null) ElectiveCourseHeader.Text = ElectiveSubjectList.SelectedItem.Text;
        setEverything(false, false, false, false, true, false, false, true, false);
        ChangeDisplayedSemesterHelper(ElectiveYearList, ElectiveSemesterList);
    } //ends CreateElectiveChangeDisplayedSemester

    /// <summary>
    /// AddElectiveChangeDisplayedSemester()
    /// 
    /// Updates all the semester lists on the page to reflect the appropriate semester to display (depending on start date)
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddElectiveChangeDisplayedSemester(object sender, EventArgs e)
    {
        //Change state of elements
        //Keep in Add Elective view
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        //borderStyle.Text = "<style>.boxBorder {border-bottom:2px solid #000000;}</style>";
        HeaderText.Text = "Add An Elective To Template";
        setEverything(false, true, false, false, false, false, false, true, false);
        ChangeDisplayedSemesterHelper(AddElectiveYearList, AddElectiveSemesterList);
    } //ends AddElectiveChangeDisplayedSemester

    private void setChooseTemplateView(bool state)
    {
        //Related elements
        ChooseTemplatePanel.Visible = state;
        ChooseTemplatePanel.Enabled = state;
    }
    private void setAddCourseView(bool state)
    {
        //Related elements
        AddCourseTable1.Visible = state;
        AddCourseTable1.Enabled = state;
        AddCourseTable2.Visible = state;
        AddCourseTable2.Enabled = state;
    }
    private void setAddElectiveView(bool state)
    {
        //Related elements
        AddExistingElectiveTable1.Visible = state;
        AddExistingElectiveTable1.Enabled = state;
        
    }
    private void setCreateElectiveView(bool state)
    {
        //Related Elements, tables called AddElective because
        //that was original name/purpose
        AddElectiveTable1.Visible = state;
        AddElectiveTable1.Enabled = state;
        AddElectiveTable2.Visible = state;
        AddElectiveTable2.Enabled = state;
        AddElectiveTable3.Visible = state;
        AddElectiveTable3.Enabled = state;
        AddElectiveLowerHeader.Visible = state;
        AddElectiveLowerHeader.Enabled = state;
    }
    private void setGraphicalView(bool state)
    {
        //Related elements
        GraphicalViewPanel.Enabled = state;
        GraphicalViewPanel.Visible = state;
        LeftButton.Enabled = state;
        LeftButton.Visible = state;
        RightButton.Enabled = state;
        RightButton.Visible = state;
    }
    private void setListView(bool state)
    {
        //Related elements
        ListViewPanel.Visible = state;
        ListViewPanel.Enabled = state;
        ListViewOptionsTable.Visible = state;
        ListViewOptionsTable.Enabled = state;
    }
    // setPageControls
    //
    // This functions enables/disables the buttons on this ASPX page
    private void setPageControls(bool state, bool cancelState, bool homeState)
    {
        //Other page elements
        TemplateName.Enabled = state;
        AddCourse.Enabled = state;
        AddElective.Enabled = state;
        CreateElective.Enabled = state;
        ViewRadio.Enabled = state;
        PrintButton.Enabled = state;
        //Cancel Button
        CancelButton.Enabled = cancelState;
        CancelButton.Visible = cancelState;
        //Home Button
        HomeButton.Enabled = homeState;
    }

    /// <summary>
    /// searchForCourseToRemove()
    /// 
    /// Deletes a course or elective in list view
    /// </summary>
    private void searchForCourseToRemove()
    {
        //Find the course/elective
        

        String termCode = SharedFunctions.convertToTermCode(MoveYearList.SelectedItem.Text, MoveCourseList.SelectedItem.Text);
        List<Course> courses = populateCourses();
        List<Elective> electives = populateElectives();
        if (ListViewSelectedCourse.Text.Substring(0, 1).Equals("c"))
        {
            String courseID = ListViewSelectedCourse.Text.Substring(1);
            foreach (Course c in courses)
            {
                if (c.getCourseID() == courseID)
                {
                    //Update the course
                    if (StoredProcedures.removeCourseFromTemplate(Session["Advisor_templateID"].ToString(), courseID.ToString()) == StoredProcedures.FAILURE)
                    {
                        //error condition
                    }
                    return;
                }
            }
        }
        else
        {
            String electiveAndCourseID = ListViewSelectedCourse.Text;
            int sloc = electiveAndCourseID.IndexOf("%");
            String selectedCourseID = electiveAndCourseID.Substring(sloc + 1);
            int electiveID = Convert.ToInt32(electiveAndCourseID.Substring(1, sloc - 1));
            foreach (Elective e in ((List<Elective>)Session["electives"]))
            {
                if (e.getElectiveID() == electiveID && e.getSelectedCourseID() == selectedCourseID)
                {
                    //Update the elective
                    if (StoredProcedures.removeElectiveFromTemplate(Session["Advisor_templateID"].ToString(), e.getElectiveID().ToString(), e.getSelectedCourseID().ToString()) == StoredProcedures.FAILURE)
                    {
                        //error condition
                    }
                    return;
                }
            }
        }
    } // end searchForCourseToRemove()

    /// MoveCourseButton_Click()
    /// 
    /// Moves a course in List View
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void MoveCourseButton_Click(object sender, EventArgs e)
    {
        //If there's no selected course, just return
        if (ListViewSelectedCourse.Text == "")
            return;
        searchForCourseToModify();
        generateListViewTable();
    }// end MoveCourseButton_Click()

    /// ManageCourseButton_Click()
    /// 
    /// Redirects the user to the ManageCourse page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ManageCourseButtonLV_Click(object sender, EventArgs e)
    {
        String cid = ListViewSelectedCourse.Text;
        if (cid[0] == 'c')
        {
            Response.Redirect("ManageCourse.aspx?cid=" + cid.Substring(1));
        }
        else if (cid[0] == 'e')
        {
            cid = cid.Substring(1, cid.IndexOf("%") - 1);
            //get the page setup for the create elective view
            CreateElective_Click(sender, e);
            //get current elective's name and choices to populate lists
            Dictionary<String, object> result = StoredProcedures.getElectiveName(cid);
            ElectiveName.Text = (String)result["name"];
            ElectiveCourseList.Items.Clear();
            List<Dictionary<String, object>> choices = StoredProcedures.getElectiveChoices(cid);
            foreach (Dictionary<String, object> i in choices)
            {
                ElectiveCourseList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
            }
            //set the electivemanagelabel to the electiveID so the elective is edited and not recreated
            ElectiveManageLabel.Text = cid;
        }
    } // end ManageCourseButtonLV_Click()

    /// <summary>
    /// RemoveCourseButton_Click()
    /// 
    /// Removes a course in List View
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void RemoveCourseButtonLV_Click(object sender, EventArgs e)
    {
        if (ListViewSelectedCourse.Text == "")
            return;
        searchForCourseToRemove();
        generateListViewTable();
    } // end RemoveCourseButton_Click()

    /// <summary>
    /// searchForCourseToModify()
    /// 
    /// Moves a course or elective in list view
    /// </summary>
    private void searchForCourseToModify()
    {
        //Find the course/elective
        List<Course> courses = populateCourses();
        List<Elective> electives = populateElectives();
        String termCode = SharedFunctions.convertToTermCode(MoveYearList.SelectedItem.Text, MoveCourseList.SelectedItem.Text);
        if (ListViewSelectedCourse.Text.Substring(0, 1).Equals("c"))
        {
            String courseID = ListViewSelectedCourse.Text.Substring(1);
            foreach (Course c in courses)
            {
                if (c.getCourseID() == courseID)
                {
                    //Update the course's term code
                    if (StoredProcedures.updateCourseInTemplate(Session["Advisor_templateID"].ToString(), courseID.ToString(), termCode) == StoredProcedures.FAILURE)
                    {
                        //error condition
                    }
                    return;
                }
            }
        }
        else
        {
            //split the text into the electiveID and selectedCourseID 
            String electiveAndCourseID = ListViewSelectedCourse.Text;
            int sloc = electiveAndCourseID.IndexOf("%");
            String selectedCourseID = electiveAndCourseID.Substring(sloc + 1);
            int electiveID = Convert.ToInt32(electiveAndCourseID.Substring(1, sloc - 1));
            foreach (Elective e in electives)
            {
                if (e.getElectiveID() == electiveID && e.getSelectedCourseID() == selectedCourseID)
                {
                    //Update the elective's term code
                    if (StoredProcedures.updateElectiveTermInTemplate(Session["Advisor_templateID"].ToString(), e.getElectiveID().ToString(), e.getCourseID().ToString(), termCode) == StoredProcedures.FAILURE)
                    {
                        //error condition
                    }
                    return;
                }
            }
        }
    } // end searchForCourseToModify()

    /// <summary>
    /// populateCourses()
    /// 
    /// Gets all the courses in an advisee's schedule (the selected advisee in the drop down list) and returns them in a list of courses
    /// </summary>
    /// <returns>A list of all the courses in the student's schedule</returns>
    private List<Course> populateCourses()
    {
        List<Course> courses = new List<Course>();
        //List<Dictionary<String, Object>> results = StoredProcedures.getTemplateCourseInfo(TemplateList.SelectedValue);
        if (Session["Advisor_templateID"] == null) return courses;
        List<Dictionary<String, Object>> results = StoredProcedures.getTemplateCourseInfo(Session["Advisor_templateID"].ToString());
        foreach (Dictionary<String, Object> i in results)
        {
            Course newCourse = new Course("" + i["courseID"], "" + i["dpt"], "" + i["num"], "" + i["name"], Convert.ToDouble(i["credits"]), "" + i["term"]);
            courses.Add(newCourse);
        }
        return courses;
    } //end populateCourses()

    /// <summary>
    /// populateElectives()
    /// 
    /// Gets all the electives in an advisee's schedule (the selected value in the drop down list) and returns them in a list of electives
    /// </summary>
    /// <returns>A list of all the electives in the student's schedule</returns>
    private List<Elective> populateElectives()
    {
        List<Elective> electives = new List<Elective>();
        //List<Dictionary<String, Object>> results = StoredProcedures.getTemplateElectiveInfo(TemplateList.SelectedValue);
        if (Session["Advisor_templateID"] == null) return electives;
        List<Dictionary<String, Object>> results = StoredProcedures.getTemplateElectiveInfo(Session["Advisor_templateID"].ToString());
        foreach (Dictionary<String, Object> i in results)
        {
            Course newCourse = new Course("" + i["selectedCourseID"], "" + i["dpt"], "" + i["num"], "" + i["name"], Convert.ToDouble(i["credits"]), "" + i["term"]);
            Elective newElective = new Elective(Convert.ToInt32(i["electiveID"]), "" + i["electiveName"], newCourse);
            List<Dictionary<String, Object>> results2 = StoredProcedures.getElectiveChoices(newElective.getElectiveID().ToString());
            foreach (Dictionary<String, Object> i2 in results2)
            {
                Course newCourseInElective = new Course("" + i2["courseID"], "" + i2["dpt"], "" + i2["num"], "" + i2["name"], Convert.ToDouble(i2["credits"]), "" + i["term"]);
                newElective.addCourse(newCourseInElective);
            }
            electives.Add(newElective);
        }
        return electives;
    } //end populateElectives()

    /// <summary>
    /// HomeButton_Click()
    /// 
    /// Redirects to the advisor default page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void HomeButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Advisor/Default.aspx");
    } //ends HomeButton_Click()

    /// <summary>
    /// HelpButton_Click()
    /// 
    /// Redirects to the advisor help page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void HelpButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Advisor/Help.aspx");
    } //end HelpButton_Click()

    /// <summary>
    /// PrintButton_Click()
    /// 
    /// Called when user clicks the Print button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void PrintButton_Click(object sender, EventArgs e)
    {
        String uid = (String)Session["Advisor_templateID"];
        String path = Server.MapPath("~/PDFs") + "/Template" + uid + ".pdf";
        String name = TemplateName.Text;
        name = name.Replace(' ', '_');
        List<Course> courses = populateCourses();
        List<Elective> electives = populateElectives();
        SharedFunctions.generatePDF(uid, path, courses, electives, true);

        try
        {
            WebClient req = new WebClient();
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.Buffer = true;
            Response.AddHeader("Content-Disposition", "attachment;filename=Template_" + name + ".pdf");
            byte[] data = req.DownloadData(path);
            Response.BinaryWrite(data);
            Response.End();
        }
        catch (Exception ex)
        {
            //Do nothing on exception
        }
        finally
        {
            File.Delete(path);
        }
    } //end PrintButton_Click()

    /// <summary>
    /// ViewTemplateButton_Click()
    /// 
    /// Views the selected template and displays the appropriate information on the page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ViewTemplateButton_Click(object sender, EventArgs e)
    {
        //Take selected template's ID, populate lists using that
        if (TemplateList.SelectedItem != null)
        {
            colorStyle.Text = "";
            TemplateInfoBox.Enabled = true;
            TemplateInfoBox.Visible = true;
            ChooseTemplatePanel.Visible = false;
            ChooseTemplatePanel.Enabled = false;
            TemplateName.Text = TemplateList.SelectedItem.Text;
            HeaderText.Text = TemplateName.Text;
            String selectedTemplateID = TemplateList.SelectedValue;
            Session["Advisor_templateID"] = selectedTemplateID;
            if (ViewRadio.SelectedIndex == 0) initializeJavaScript();
            else generateListViewTable();
        }
        else
        {
            //Change state of elements
            //Keep page in Choose Template View
            colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
            HeaderText.Text = "Choose Template to Edit";
            setEverything(false, false, false, false, false, true, false, false, true);
        }
    } //end ViewTemplateButton_Click()

    /// <summary>
    /// ViewTemplateButton_Click()
    /// 
    /// Views the selected template and displays the appropriate information on the page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void CopyTemplateButton_Click(object sender, EventArgs e)
    {
        //Take selected template's ID, make a new template, 
        if (TemplateList.SelectedItem != null)
        {
            colorStyle.Text = "";
            TemplateInfoBox.Enabled = true;
            TemplateInfoBox.Visible = true;
            ChooseTemplatePanel.Visible = false;
            ChooseTemplatePanel.Enabled = false;
            String selectedTemplateID = TemplateList.SelectedValue;
            List<Dictionary<String, Object>> courses = StoredProcedures.getTemplateCourseInfo(selectedTemplateID);
            List<Dictionary<String, Object>> electives = StoredProcedures.getTemplateElectiveInfo(selectedTemplateID);
            String templateName = StoredProcedures.getTemplateName(selectedTemplateID)["name"].ToString();
            String newTemplateName = "Copy of " + templateName;
            TemplateName.Text = newTemplateName;
            HeaderText.Text = TemplateName.Text;
            StoredProcedures.makeNewTemplate(newTemplateName);
            String newTemplateID = StoredProcedures.getLastTemplateID().ToString();
            Session["Advisor_templateID"] = newTemplateID;
            //Copy courses
            foreach(Dictionary<String, Object> course in courses)
            {
                StoredProcedures.insertCourseIntoTemplate(newTemplateID.ToString(), course["courseID"].ToString(), course["term"].ToString());
            }
            foreach (Dictionary<String, Object> elective in electives)
            {
                StoredProcedures.insertElectiveIntoTemplate("" + elective["electiveID"], newTemplateID.ToString(), "" + elective["selectedCourseID"], "" + elective["term"]);
            }
            if (ViewRadio.SelectedIndex == 0) initializeJavaScript();
            else generateListViewTable();
        }
        else
        {
            //Change state of elements
            //Keep page in Choose Template View
            colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
            HeaderText.Text = "Choose Template to Edit";
            setEverything(false, false, false, false, false, true, false, false, true);
        }
    } //end ViewTemplateButton_Click()

    /// <summary>
    /// AddCourse_Click()
    /// 
    /// Displays the appropriate elements when the user hits the create course button
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddCourse_Click(object sender, EventArgs e)
    {
        //Populate Subject List
        Dictionary<String, String> courses = SharedFunctions.getDptAcronymToString();
        SubjectList.Items.Clear();
        SubjectList.Items.Add(new ListItem("All Courses"));
        foreach (String s in courses.Keys)
        {
            SubjectList.Items.Add(new ListItem(courses[s], s));
        }
        //Clear Course list
        CourseList.Items.Clear();
        //Change Content
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add A Course To Template";
        //Change State of elements
        CancelButton.Text = "Cancel";
        setEverything(true, false, false, false, false, false, false, true, false);
    } // end AddCourse_Click()

    /// <summary>
    /// CreateElective_Click()
    /// ERIC todo
    /// 
    /// Displays the appropriate elements when the user htis the Create Elective button from the left column menu
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void CreateElective_Click(object sender, EventArgs e)
    {
        //Populate Subject List
        Dictionary<String, String> courses = SharedFunctions.getDptAcronymToString();
        ElectiveSubjectList.Items.Clear();
        ElectiveSubjectList.Items.Add(new ListItem("All Courses"));
        foreach (String s in courses.Keys)
        {
            ElectiveSubjectList.Items.Add(new ListItem(courses[s], s));
        }
        //Change Content
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Create An Elective for the Template";
        //Change State of elements
        setEverything(false, false, false, false, true, false, false, true, false);
        
    } // end CreateElective_Click()

    /// <sumary>
    /// AddElective_Click()
    /// ERIC todo
    /// Displays the appropriate elements when the user hits the "Add Existing Elective" button from the left column menu
    /// </sumary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddElective_Click(object sender, EventArgs e)
    {
     
        //Change Content
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add An Elective To Template";

        //get list of electives from db and display in ElectiveListBox
        ElectiveListBox.Items.Clear();
        List<Dictionary<String, Object>> results;
        results = StoredProcedures.getListOfElectives();
        foreach (Dictionary<String, Object> elecs in results)
        {
            ListItem elective = new ListItem(elecs["name"]+"", elecs["electiveID"].ToString());
            ElectiveListBox.Items.Add(elective);
        }
       
        
        //Change State of elements
        setEverything(false, true, false, false, false, false, false, true, false);
    }

    /// <sumary>
    /// ViewElectiveButton_Click()
    /// 
    /// Displays the appropriate elements when the user hits the View button
    /// </sumary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ViewElectiveButton_Click(object sender, EventArgs e)
    {

        if (ElectiveListBox.SelectedIndex == -1)
        {
            return;
        }

        //get currently selected electiveID and get list of courses that satisfy it to display
        string electiveID = ElectiveListBox.SelectedItem.Value;
        SatisfyCourseList.Items.Clear();
        List<Dictionary<String, Object>> results;
        results = StoredProcedures.getElectiveChoices(electiveID);
        foreach (Dictionary<String, Object> i in results)
        {
            SatisfyCourseList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
        }

        //Change Content
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add An Elective To Template";
        setEverything(false, true, false, false, false, false, false, true, false);
      
    }

    /// <sumary>
    /// AddSelectedElectiveButton_Click()
    /// ERIC todo
    /// Adds the selected preexisting elective to the template in the specified semester/year
    /// </sumary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddSelectedElectiveButton_Click(object sender, EventArgs e)
    {
        ///howto
        //Create a template to put stuff in if it's not already created
        UpdateTemplateName_Click(sender, e);
        //error check that an elective is selected
        if (ElectiveListBox.SelectedIndex == -1)
        {
            MessageBox.Show("Please select an elective");
            AddElective_Click(sender, e);
            return;
        }
        if (AddElectiveSemesterList.SelectedIndex == -1 || AddElectiveYearList.SelectedIndex == -1)
        {
            MessageBox.Show("Please select a semester and year");
            AddElective_Click(sender, e);
            return;
        }

        String electiveID = ElectiveListBox.SelectedItem.Value;
        String templateID = (String)Session["Advisor_templateID"]; //Session["Advisor_templateID"].ToString()
        String termCode = SharedFunctions.convertToTermCode(AddElectiveYearList.SelectedItem.Text, AddElectiveSemesterList.SelectedItem.Text);
        //use electiveID to get courses for elective, then use first one to add as selected
        List<Dictionary<String, Object>> result;
        result = StoredProcedures.getElectiveChoices(electiveID);
        String courseID = "";
        Boolean insertionFailure = true;
        foreach (Dictionary<String, Object> i in result)
        {
            courseID = "" + i["courseID"];
            //insertElectiveIntoTemplate();
            if (StoredProcedures.insertElectiveIntoTemplate(electiveID, templateID, courseID, termCode) != StoredProcedures.FAILURE)
            {
                insertionFailure = false;
                break;
            }
        }
        if (insertionFailure)
        {
            MessageBox.Show("This elective is already in the schedule with every possible course");
        }
        

        //return to view template and display violations
        CancelButton_Click(sender, e);
        if (ViewRadio.SelectedIndex == 0)
        {
            initializeJavaScript();
        }
        else
        {
            generateListViewTable();
        }
        
    }

    /// <summary>
    /// CancelButton_Click()
    /// 
    /// Displays the appropriate elements when the user hits the cancel button
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void CancelButton_Click(object sender, EventArgs e)
    {
        //Change Content
        colorStyle.Text = "";
        //This needs to change...
        HeaderText.Text = "Year 1 - Year 3";
        CourseHeader.Text = "";
        ElectiveCourseHeader.Text = "";
        //Change State of elements
        //setRightLeftButtons(true);
        //setCancelButton(false);
        //AddCourseTable1.Visible = false;
        //AddCourseTable1.Enabled = false;
        //AddCourseTable2.Visible = false;
        //AddCourseTable2.Enabled = false;
        //setElectiveTable(false);
        //setPopUpButtons(true);
        //if (ViewRadio.SelectedIndex == 0) generateGraphicalView();
        //else generateListViewTable();
    } // end CancelButton_Click()

    /// <summary>
    /// FindCoursesButton_Click()
    /// 
    /// Displays the appropriate elements when the user presses the find courses button in the Add Course page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void FindCoursesButton_Click(object sender, EventArgs e)
    {
        //Error checking (if nothing is selected, then set the selected subject to be the first, which is all courses)
        if (SubjectList.SelectedIndex == -1)
        {
            SubjectList.SelectedIndex = 0;
        }
        //Populate the course list with the appropriate courses
        CourseList.Items.Clear();
        List<Dictionary<String, Object>> results;
        if (SubjectList.SelectedIndex == 0)
        {
            results = StoredProcedures.getListOfCourses();
        }
        else
        {
            results = StoredProcedures.getListOfCoursesFiltered(SubjectList.SelectedValue);
        }
        foreach (Dictionary<String, Object> i in results)
        {
            CourseList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
        }
        //Change State of elements
        //Keep in Add Course View
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add A Course To Template";
        CourseHeader.Text = SubjectList.SelectedItem.Text;
        setEverything(true, false, false, false, false, false, false, true, false);
        //Update the semesters displayed
        ChangeDisplayedSemesterHelper(ElectiveYearList, ElectiveSemesterList);
    } // end FindCoursesButton_Click()

    /// <summary>
    /// ElectiveFindCoursesButton_Click()
    /// 
    /// Displays the appropriate elements when the user clicks the find courses button on the elective page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ElectiveFindCoursesButton_Click(object sender, EventArgs e)
    {
        //Error checking (if nothing is selected, then set the selected subject to be the first, which is all subjects)
        if (ElectiveSubjectList.SelectedIndex == -1)
        {
            ElectiveSubjectList.SelectedIndex = 0;
        }
        ElectiveOptionsList.Items.Clear();
        //Populate the list of course options appropriately
        List<Dictionary<String, Object>> results;
        if (ElectiveSubjectList.SelectedIndex == 0)
        {
            results = StoredProcedures.getListOfCourses();
        }
        else
        {
            results = StoredProcedures.getListOfCoursesFiltered(ElectiveSubjectList.SelectedValue);
        }
        foreach (Dictionary<String, Object> i in results)
        {
            ElectiveOptionsList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
        }
        //Change state of elements
        //Keep in Add Elective view
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add An Elective To Template";
        ElectiveCourseHeader.Text = ElectiveSubjectList.SelectedItem.Text;
        setEverything(false, false, false, false, true, false, false, true, false);
    } // end ElectiveFindCoursesButton_Click()

    /// <summary>
    /// AddToScheduleButton_Click()
    /// 
    /// Adds a selected course to a template
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void AddToScheduleButton_Click(object sender, EventArgs e)
    {
        //Create a template to put stuff in if it's not already created
        UpdateTemplateName_Click(sender, e);
        //If either of the necessary items to add a course are not selected, return out
        if (CourseList.SelectedItem == null || YearList.SelectedItem == null)
        {
            //Return to the same add course page and take no additional action
            MessageBox.Show("A course and year must be selected");
            AddCourse_Click(sender, e);
            return;
        }
        //Add the course to the session variable to hold added courses
        Dictionary<String, Object> result = StoredProcedures.getCourse(CourseList.SelectedValue);
        if (result != null)
        {
            String termCode = SharedFunctions.convertToTermCode(YearList.SelectedItem.Text, SemesterList.SelectedItem.Text);
            if (StoredProcedures.insertCourseIntoTemplate(Session["Advisor_templateID"].ToString(), result["courseID"].ToString(), termCode) == StoredProcedures.FAILURE)
            {
                MessageBox.Show("Could not add course for some reason - Already exists in the schedule");
                //error condition
            }
        }
        else
        {
            //error condition
        }
        //Return to viewing the template
        CancelButton_Click(sender, e);
        if (ViewRadio.SelectedIndex == 0)
        {
            initializeJavaScript();
        }
        else
        {
            generateListViewTable();
        }
        
    } // end AddToScheduleButton_Click()

    /// <summary>
    /// ElectiveRemoveButton_Click()
    /// 
    /// Removes a possible course choice from an Elective when on the add elective page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ElectiveRemoveButton_Click(object sender, EventArgs e)
    {
        if (ElectiveCourseList.SelectedItem != null)
        {
            ElectiveOptionsList.Items.Add(ElectiveCourseList.SelectedItem);
            ElectiveCourseList.Items.Remove(ElectiveCourseList.SelectedItem);
            ElectiveOptionsList.ClearSelection();
            ElectiveCourseList.ClearSelection();
        }
        //Change state of elements
        //Keep in Add Elective view
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        HeaderText.Text = "Add An Elective To Template";
        if (ElectiveSubjectList.SelectedItem != null) ElectiveCourseHeader.Text = ElectiveSubjectList.SelectedItem.Text;
        setEverything(false, false, false, false, true, false, false, true, false);
    }
    // end ElectiveRemoveButton_Click()

    /// <summary>
    /// UpdateTemplateName_Click()
    /// 
    /// Updates a template name
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void UpdateTemplateName_Click(object sender, EventArgs e)
    {
        int templateID = -1;
        bool isDuplicate = false; //a bool which will be true if the template name is being used by another template

        //Check if the template name is already in the database
        List<Dictionary<String, Object>> templates = StoredProcedures.getTemplates();
        foreach (Dictionary<String, Object> tempt in templates)
        { 
            //if there is already a template with our name and it's not us, pop an error message
            //key is template id and object is name
            if((tempt.ContainsValue(TemplateName.Text))){
                if ((Session["Advisor_templateID"] == null) || !(Session["Advisor_templateID"].Equals(tempt["templateID"].ToString())))
                {
                    //Alert the user and exit this function without creating/updating a template
                    MessageBox.Show("This template name is already in use. Please choose another name.");
                    isDuplicate = true;
                }
            }
        }

        if (!isDuplicate)
        {
            if (Session["Advisor_templateID"] == null)//Create new template
            {
                //Make a template and get its ID from the database
                if (StoredProcedures.makeNewTemplate(TemplateName.Text) == StoredProcedures.FAILURE)
                {
                    //error condition
                }
                templateID = StoredProcedures.getLastTemplateID();
            }
            else // Modify an existing template
            {
                templateID = Convert.ToInt32(Session["Advisor_templateID"]);
                if (!templateID.Equals("")) // don't change the template name if there is no name
                    if (StoredProcedures.changeTemplateName(TemplateName.Text, templateID.ToString()) == StoredProcedures.FAILURE)
                    {
                        //error condition
                    }
            }
            Session["Advisor_templateID"] = templateID.ToString();
        }
    }

    /// <summary>
    /// ElectiveFinishButtonClick()
    /// 
    /// Creates an elective and adds it to an advisee's schedule
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ElectiveFinishButton_Click(object sender, EventArgs e)
    {
        //Create a template to put stuff in if it's not already created
        UpdateTemplateName_Click(sender, e);
        if (ElectiveName.Text == "")
        {
            MessageBox.Show("Please supply an elective name");
            CreateElective_Click(sender, e);
            return;
        }
        if (ElectiveCourseList.Items.Count == 0)
        {
            MessageBox.Show("The elective must have at least one possible course");
            CreateElective_Click(sender, e);
            return;
        }
        //Check if the template name is already in the database
        foreach (Elective elective in electiveList)
        {
            //if there is already an elective with this name, send an error and do nothing
            if (elective.getElectiveName().Equals(ElectiveName.Text))
            {
                //Alert the user and exit this function without creating/updating a template
                MessageBox.Show("This elective name is already in use. Please choose another name.");
                CreateElective_Click(sender, e);
                return;
            }
        }
        if (ElectiveManageLabel.Text.Equals(""))
        {
            if (StoredProcedures.makeNewElective(ElectiveName.Text) == StoredProcedures.FAILURE)
            {
                //error condition
            }
            //Get the ID of the elective just made
            int lastElectiveID = SharedFunctions.getLastElectiveID();
            //Get the term code from the user choices
            String term = SharedFunctions.convertToTermCode(ElectiveYearList.SelectedItem.Text, ElectiveSemesterList.SelectedItem.Text);
            // Get the first course in the elective course choice list and set it as the first selected course for the elective
            Dictionary<String, Object> result = StoredProcedures.getCourse(ElectiveCourseList.Items[0].Value);
            //Insert the elective into the schedule
            if (StoredProcedures.insertElectiveIntoTemplate(lastElectiveID.ToString(), Session["Advisor_templateID"].ToString(), result["courseID"].ToString(), term) == StoredProcedures.FAILURE)
            {
                //error condition
            }
            //Insert all the selected courses into the elective
            foreach (ListItem i in ElectiveCourseList.Items)
            {
                if (StoredProcedures.addCourseToElective(lastElectiveID.ToString(), i.Value) == StoredProcedures.FAILURE)
                {
                    //error condition
                }
            }
        }
        else
        {
            Dictionary<String, Object> result = StoredProcedures.getCourse(ElectiveCourseList.Items[0].Value);
            String templateID = (String)Session["Advisor_templateID"];
            String eid = ElectiveManageLabel.Text;
            String selectedCourseID = "" + result["courseID"];
            String term = SharedFunctions.convertToTermCode(ElectiveYearList.SelectedItem.Text, ElectiveSemesterList.SelectedItem.Text);
            StoredProcedures.updateElectiveInTemplate(templateID, eid, selectedCourseID, term);

            List<Dictionary<String, object>> currentChoices = StoredProcedures.getElectiveChoices(eid);
            foreach (ListItem i in ElectiveCourseList.Items)
            {
                bool exists = false;
                foreach (Dictionary<String, object> j in currentChoices)
                {
                    String cid = "" + j["courseID"];
                    if (i.Value.Equals(cid))
                    {
                        exists = true;
                        break;
                    }
                }
                if (exists) continue;
                if (StoredProcedures.addCourseToElective(eid, i.Value) == StoredProcedures.FAILURE)
                {
                    //error condition
                }
            }
            foreach (Dictionary<String, object> j in currentChoices)
            {
                bool exists = false;
                String cid = "" + j["courseID"];
                foreach (ListItem i in ElectiveCourseList.Items)
                {
                    if (i.Value.Equals(cid))
                    {
                        exists = true;
                        break;
                    }
                }
                if (exists) continue;
                if (StoredProcedures.removeCourseFromElective(eid, cid) == StoredProcedures.FAILURE)
                {
                    //error condition
                }
            }
        }
        if (ViewRadio.SelectedIndex == 0)
        {
            initializeJavaScript();
        }
        else
        {
            generateListViewTable();
        }
        CancelButton_Click(sender, e);
        
    }//end ElectiveFinishButton_Click

    /// <summary>
    /// ElectiveAddButton_Click()
    /// 
    /// Add a course to the list of the possible courses in an elective on the add elective page
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ElectiveAddButton_Click(object sender, EventArgs e)
    {
        if (ElectiveOptionsList.SelectedItem != null)
        {
            //add a course to the possible choices for the elective
            ElectiveCourseList.Items.Add(ElectiveOptionsList.SelectedItem);
            ElectiveOptionsList.Items.Remove(ElectiveOptionsList.SelectedItem);
            ElectiveOptionsList.ClearSelection();
            ElectiveCourseList.ClearSelection();
        }
        //Change state of elements
        //Keep in Add Elective view
        colorStyle.Text = "<style>.boxColor {background-color:#B3D9FF;}</style>";
        //borderStyle.Text = "<style>.boxBorder {border-bottom:2px solid #000000;}</style>";
        HeaderText.Text = "Add An Elective To Template";
        if(ElectiveSubjectList.SelectedItem != null) ElectiveCourseHeader.Text = ElectiveSubjectList.SelectedItem.Text;
        setEverything(false, false, false, false, true, false, false, true, false);
    }
    // end ElectiveAddButton_Click()

    /// <summary>
    /// SaveButton_Click()
    /// 
    /// Saves all the courses and electives in the Session variables and actually adds them to a template in the database
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void SaveButton_Click(object sender, EventArgs e)
    {
        int templateID;
        //Make a new template
        if (Session["Advisor_templateID"] == null)
        {
            //Make a template and get its ID from the database
            if (StoredProcedures.makeNewTemplate(TemplateName.Text) == 0)
            {
                //error condition
            }
            templateID = StoredProcedures.getLastTemplateID();
        }
        else // Modify an existing template
        {
            templateID = Convert.ToInt32(Session["Advisor_templateID"]);
            if (!templateID.Equals("")) // don't change the template name if there is no name
             StoredProcedures.changeTemplateName(TemplateName.Text, templateID.ToString());
        }
        Session["Advisor_templateID"] = templateID.ToString();
        //Put courses in the template
    } // end SaveButton_Click()

    /// <summary>
    /// generateListViewTable()
    /// 
    /// Takes the courses and electives in a student's schedule and displays the information
    /// </summary>
    private void generateListViewTable()
    {
        setListView(true);
        setGraphicalView(false);
        //Clear all currently existing controls so that we don't get multiple tables
        ListViewCourseTable.Controls.Clear();
        List<Course> courses = populateCourses();
        List<Elective> electives = populateElectives();
        SharedFunctions.displayViolations(ViolationsLabel, (List<String>)SharedFunctions.checkSchedule(null, populateCourses(), populateElectives())["violationMessages"]);
        List<Course> electivesAndCourses = new List<Course>();
        foreach (Course c in courses)
        {
            electivesAndCourses.Add(c);
        }
        foreach (Elective e in electives)
        {
            electivesAndCourses.Add(e);
        }
        int largestStartDate = 0;
        int smallestStartDate = 2;
        String largestSemester = "";
        //Determine the earliest date and also the number of years to put in the list view
        foreach (Course c in electivesAndCourses)
        {
            int term = Convert.ToInt32(c.getYear());
            if (term > largestStartDate)
            {
                largestStartDate = term;
                largestSemester = c.getSemester();
            }
        }
        int numberOfYears = largestStartDate - 1;
        if (largestSemester.Equals("Fall")) numberOfYears++;
        if (numberOfYears == 0) numberOfYears = 1;
        //Iterate for as many years as was just determined
        for (int i = smallestStartDate; i < smallestStartDate + numberOfYears; i++)
        {
            TableRow r = new TableRow();
            //Put all the fall, spring, and summer courses in their place appropriately
            for (int j = 0; j < 3; j++)
            {
                int year = i;
                TableCell c = new TableCell();
                c.Width = new Unit("33%");
                c.CssClass = "listCell";
                String semesterName = "";
                if (j == 0)
                {
                    semesterName = "Fall";
                    year--;
                }
                else if (j == 1)
                {
                    semesterName = "Spring";
                }
                else
                {
                    semesterName = "Summer";
                }
                //Create a new control on the page to add radio buttons to
                c.Controls.Add(new LiteralControl(semesterName + " " + year + "<br />"));

                double credits = 0;
                foreach (Course course in electivesAndCourses)
                {
                    if (!semesterName.Equals("Fall"))
                    {
                        if (course.getYear() == i && course.getSemester().Equals(semesterName))
                        {
                            credits += course.getCredits();
                            //Create a radio button
                            RadioButton rb = new RadioButton();
                            if (course is Elective)
                            {
                                Elective elective = course as Elective;
                                rb.Text = "Elective: " + course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "e" + elective.getElectiveID() + "%" + elective.getSelectedCourseID();
                            }
                            else
                            {
                                rb.Text = course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "c" + course.getCourseID();
                            }
                            rb.GroupName = "Schedule";
                            rb.AutoPostBack = true;
                            //Adds an event handling function to be called when the radio button is selected
                            rb.CheckedChanged += new EventHandler(getSelectedRadio);
                            c.Controls.Add(rb);
                            c.Controls.Add(new LiteralControl("<br />"));
                        }
                    }
                    else
                    {
                        if (course.getYear() == i - 1 && course.getSemester().Equals(semesterName))
                        {
                            credits += course.getCredits();
                            //Create a radio button
                            RadioButton rb = new RadioButton();
                            if (course is Elective)
                            {
                                Elective elective = course as Elective;
                                rb.Text = "Elective: " + course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "e" + elective.getElectiveID() + "%" + elective.getSelectedCourseID();
                            }
                            else
                            {
                                rb.Text = course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "c" + course.getCourseID();
                            }
                            rb.GroupName = "Schedule";
                            rb.AutoPostBack = true;
                            //Adds an event handling function to be called when the radio button is selected
                            rb.CheckedChanged += new EventHandler(getSelectedRadio);
                            c.Controls.Add(rb);
                            c.Controls.Add(new LiteralControl("<br />"));
                        }
                    }
                }
                c.Controls.Add(new LiteralControl("Credits: " + credits));
                r.Controls.Add(c);
            }
            ListViewCourseTable.Controls.Add(r);
        }
    } // end generateListViewTable()

    /// <summary>
    /// getSelectedRadio()
    /// 
    /// Event handler for radio buttons in list view
    /// </summary>
    /// <param name="sender">object sender - the radio button for which this is the event</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void getSelectedRadio(object sender, EventArgs e)
    {
        RadioButton rb = (RadioButton)sender;
        //Set an invisible field to be referred to later to determine the selected radio button
        ListViewSelectedCourse.Text = rb.ID;
    } // end getSelectedRadio()


    /// <summary>
    /// colorViolations
    ///
    /// POSSIBLE Color Values:
    ///  PASS (NO COLORING)
    ///  BORDERLINE (FCB315) //Pale Yellow (60)
    ///  FAIL (AB1E38) //Red (50)
    ///  
    /// preReq/coReq (F15E22) Orange
    /// 
    ///  NULL (NULL GRADE, RIGHT SPOT) (COLORED)    CACBC8 white/cream
    ///  MISSING (NO RECORD OF COURSE) (COLORED)   727075 grey
    ///  WRONG(COURSE RECORD IN DIFFERENT TERM, PREVIOUS OR ) (COLORED) Black 000000 
    ///  
    ///  
    /// Color those methods that are flagged for violation(s)
    /// </summary>
    /// <param name="preCoReqColoring"></param>
    public void colorViolations(Dictionary<String, Object> violations)
    {
        foreach (Control p in GraphicalViewPanel.Controls)
        {
            foreach (Control c in p.Controls)
            {
                if (c is Panel)
                {
                    foreach (Control courseBox in c.Controls)
                    {
                        if (courseBox is Panel)
                        {
                            String courseID = ((Panel)courseBox).ID.Substring(courseBox.ID.IndexOf("$") + 1);
                            if (violations.ContainsKey(courseID))
                            {
                                String courseViolation = (String)((Dictionary<String, Object>)violations[courseID])["violation"];
                                if (courseViolation == "FAIL")
                                {
                                    ((Panel)courseBox).CssClass = "courseFailCSS";
                                }
                                else if (courseViolation == "BORDERLINE")
                                {
                                    ((Panel)courseBox).CssClass = "courseBorderlineCSS";
                                }
                                else if (courseViolation == "preReq" || courseViolation == "coReq")
                                {
                                    ((Panel)courseBox).CssClass = "precoreqViolationsCSS";
                                }
                                else if (courseViolation == "NULL")
                                {
                                    ((Panel)courseBox).CssClass = "courseNullCSS";
                                }
                                else if (courseViolation == "MISSING")
                                {
                                    ((Panel)courseBox).CssClass = "courseMissingCSS";
                                }
                                else if (courseViolation == "WRONG")
                                {
                                    ((Panel)courseBox).CssClass = "courseWrongCSS";
                                }
                                else
                                {
                                    ((Panel)courseBox).CssClass = "courseLabelCSS";
                                }

                            }
                            else
                            {
                                ((Panel)courseBox).CssClass = "courseLabelCSS";
                            }
                        }
                    }
                }
            }//end of foreach Control
        }//end foreach Panel
        return;
    }//end colorViolations()



    /////////////////////////
    //GRAPHICAL VIEW APPLET//
    /////////////////////////
    /// <summary>
    /// initializeJavaScript()
    /// Graphical View Function
    /// 
    /// Initializes and dynamically creates the pageLoad function for JavaScript and course boxes.
    /// </summary>
    private void initializeJavaScript()
    {
        //Set header of main box to display visible years
        int y = Convert.ToInt32((String)Session["Advisor_templateYearGV"]);
        int y2 = y + 2;
        HeaderText.Text = "Years " + y + " - " + y2;

        //Populate lists of courses and electives
        courseList = populateCourses();
        electiveList = populateElectives();

        //Clear semester regions to ensure always starting fresh
        clearSemesterRegions();

        //Dynamic JavaScript - begin HTML script tag and begin pageLoad function
        JavaScriptPageLoad.Text = "<script type='text/javascript'> function pageLoad() { ";
        //Initialize each part of GV and its associated JavaScript
        initializeSemesterRegions();
        initializeCourseBoxes();
        initializeElectiveBoxes();
        initializeSemesterLabels();
        finalizeSemesterRegions();
        //Dynamic JavaScript - end the pageLoad function and end the HTML tag
        JavaScriptPageLoad.Text += "} </script>";

        //get violations to display and color
        Dictionary<String, Object> optimizer = SharedFunctions.checkSchedule(null, courseList, electiveList);
        SharedFunctions.displayViolations(ViolationsLabel, (List<String>)optimizer["violationMessages"]);
        colorViolations(optimizer);
    } //end initializeJavaScript()

    /// <summary>
    /// clearSemesterRegions()
    /// Graphical View Function
    /// 
    /// Resets semester regions and removes all course boxes and labels.
    /// </summary>
    private void clearSemesterRegions()
    {
        //Clear old courses
        SemesterRegion1.Controls.Clear();
        SemesterRegion2.Controls.Clear();
        SemesterRegion3.Controls.Clear();
        SemesterRegion4.Controls.Clear();
        SemesterRegion5.Controls.Clear();
        //Re-add center style
        SemesterRegion1.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("<center>"));
        //Re-add labels
        SemesterRegion1.Controls.Add(SemesterLabel1);
        SemesterRegion2.Controls.Add(SemesterLabel2);
        SemesterRegion3.Controls.Add(SemesterLabel3);
        SemesterRegion4.Controls.Add(SemesterLabel4);
        SemesterRegion5.Controls.Add(SemesterLabel5);
        //Re-add Credit Labels
        SemesterRegion1.Controls.Add(SemesterCreditsLabel1);
        SemesterRegion2.Controls.Add(SemesterCreditsLabel2);
        SemesterRegion3.Controls.Add(SemesterCreditsLabel3);
        SemesterRegion4.Controls.Add(SemesterCreditsLabel4);
        SemesterRegion5.Controls.Add(SemesterCreditsLabel5);
        //Re-initialize credits labels
        SemesterCreditsLabel1.Text = "Credits: 0";
        SemesterCreditsLabel2.Text = "Credits: 0";
        SemesterCreditsLabel3.Text = "Credits: 0";
        SemesterCreditsLabel4.Text = "Credits: 0";
        SemesterCreditsLabel5.Text = "Credits: 0";
        //Re-add move labels
        SemesterRegion1.Controls.Add(new LiteralControl("<span id=\"SemMove1\">Moving...</span></center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("<span id=\"SemMove2\">Moving...</span></center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("<span id=\"SemMove3\">Moving...</span></center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("<span id=\"SemMove4\">Moving...</span></center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("<span id=\"SemMove5\">Moving...</span></center>"));
    } //end clearSemesterRegions()

    /// <summary>
    /// finalizeSemesterRegions()
    /// Graphical View Function
    /// 
    /// Calculates and adds padding to semester regions and adds the bottom semester labels.
    /// </summary>
    private void finalizeSemesterRegions()
    {
        //count maximum number of panels in each semester region
        int max = 0;
        int[] counts = { 0, 0, 0, 0, 0 };
        foreach (Control c in SemesterRegion1.Controls)
        {
            if (c is Panel) counts[0] = counts[0] + 1;
        }
        if (counts[0] > max) max = counts[0];
        foreach (Control c in SemesterRegion2.Controls)
        {
            if (c is Panel) counts[1] = counts[1] + 1;
        }
        if (counts[1] > max) max = counts[1];
        foreach (Control c in SemesterRegion3.Controls)
        {
            if (c is Panel) counts[2] = counts[2] + 1;
        }
        if (counts[2] > max) max = counts[2];
        foreach (Control c in SemesterRegion4.Controls)
        {
            if (c is Panel) counts[3] = counts[3] + 1;
        }
        if (counts[3] > max) max = counts[3];
        foreach (Control c in SemesterRegion5.Controls)
        {
            if (c is Panel) counts[4] = counts[4] + 1;
        }
        if (counts[4] > max) max = counts[4];

        //Set maximum height of each semester region appropriately
        max = (max / 4) + 1;
        max = max * 100;
        SemesterRegion1.Style["height"] = max + "%";
        SemesterRegion2.Style["height"] = max + "%";
        SemesterRegion3.Style["height"] = max + "%";
        SemesterRegion4.Style["height"] = max + "%";
        SemesterRegion5.Style["height"] = max + "%";

        //Add filler boxes to pad each region
        for (int index = 0; index < 5; index++)
        {
            int limit = max / 100;
            limit = limit * 4;
            limit = limit - 1;
            limit = limit - counts[index];
            for (int i = 0; i < limit; i++)
            {
                Panel p = new Panel();
                p.CssClass = "courseFillerCSS";
                switch (index)
                {
                    case 0:
                        SemesterRegion1.Controls.Add(p);
                        SemesterRegion1.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 1:
                        SemesterRegion2.Controls.Add(p);
                        SemesterRegion2.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 2:
                        SemesterRegion3.Controls.Add(p);
                        SemesterRegion3.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 3:
                        SemesterRegion4.Controls.Add(p);
                        SemesterRegion4.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 4:
                    default:
                        SemesterRegion5.Controls.Add(p);
                        SemesterRegion5.Controls.Add(new LiteralControl("<br />"));
                        break;
                }
            }
        }

        //Add center style
        SemesterRegion1.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("<br /><center>"));

        //Add labels with following properties:
        //Enabled="false" BorderStyle="None" Width="90%" CssClass="labelCSS"
        for (int i = 1; i <= 5; i++)
        {
            TextBox slc = new TextBox();
            slc.Enabled = false;
            slc.BorderStyle = BorderStyle.None;
            slc.Width = new Unit("90%");
            slc.CssClass = "labelCSS";
            switch (i)
            {
                case 1:
                    slc.Text = SemesterLabel1.Text;
                    SemesterRegion1.Controls.Add(slc);
                    break;
                case 2:
                    slc.Text = SemesterLabel2.Text;
                    SemesterRegion2.Controls.Add(slc);
                    break;
                case 3:
                    slc.Text = SemesterLabel3.Text;
                    SemesterRegion3.Controls.Add(slc);
                    break;
                case 4:
                    slc.Text = SemesterLabel4.Text;
                    SemesterRegion4.Controls.Add(slc);
                    break;
                case 5:
                default:
                    slc.Text = SemesterLabel5.Text;
                    SemesterRegion5.Controls.Add(slc);
                    break;
            }

        }

        //End center styling
        SemesterRegion1.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("</center>"));
    } //end finalizeSemesterRegions()

    /// <summary>
    /// initializeCourseBoxes()
    /// Graphical View Function
    /// 
    /// Dynamically creates course boxes and places them in the appropriate semester containers.
    /// </summary>
    private void initializeCourseBoxes()
    {
        //Get currently visible year
        int y = Convert.ToInt32((String)Session["Advisor_templateYearGV"]);
        foreach (Course c in courseList)
        {
            //Get relevant course info
            String term = c.getSemester();
            int cyear = c.getYear();
            String deptNum = c.getDpt() + c.getNum();
            String termCode = SharedFunctions.convertToTermCode((String)Session["Advisor_templateYearGV"],term);

            //If current course is not within currently visible years, then skip over it
            if ((cyear < y) || (cyear > (y + 2))) continue;

            //Determine place of course on schedule
            if (cyear == y)
            {
                if (!term.Equals("Fall")) continue; //Only fall of first year is visible
                createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 1, termCode);
                UpdateSemesterCreditsLabel(1, c.getCredits());
            }
            else if (cyear == (y + 1))
            {
                if (term.Equals("Spring"))
                {
                    createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 2, termCode); //Spring of second visible year
                    UpdateSemesterCreditsLabel(2, c.getCredits());
                }
                else if (term.Equals("Summer"))
                {
                    createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 3, termCode); //Summer
                    UpdateSemesterCreditsLabel(3, c.getCredits());
                }
                else
                {
                    createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 4, termCode); //Fall
                    UpdateSemesterCreditsLabel(4, c.getCredits());
                }
            }
            else //if (cyear == (y + 2))
            {
                if (!term.Equals("Spring")) continue; //Only spring of third year is visible
                createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 5, termCode);
                UpdateSemesterCreditsLabel(5, c.getCredits());
            }
        }
    } //end initializeCourseBoxes()

    /// <summary>
    /// initializeElectiveBoxes()
    /// Graphical View Function
    /// 
    /// Dynamically creates elective boxes and places them in the appropriate semester containers.
    /// </summary>
    private void initializeElectiveBoxes()
    {
        //Get currently visible year
        int y = Convert.ToInt32((String)Session["Advisor_templateYearGV"]);
        foreach (Elective e in electiveList)
        {
            //Get relevant elective info
            String term = e.getSemester();
            int eyear = e.getYear();

            //If current elective is not within currently visible years, then skip over it
            if ((eyear < y) || (eyear > (y + 2))) continue;

            //Determine place of elective on schedule
            if (eyear == y)
            {
                if (!term.Equals("Fall")) continue; //Only fall of first year is visible
                createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 1);
                UpdateSemesterCreditsLabel(1, e.getCredits());
            }
            else if (eyear == (y + 1))
            {
                if (term.Equals("Spring"))
                {
                    createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 2); //Spring of second visible year
                    UpdateSemesterCreditsLabel(2, e.getCredits());
                }
                else if (term.Equals("Summer"))
                {
                    createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 3); //Summer
                    UpdateSemesterCreditsLabel(3, e.getCredits());
                }
                else
                {
                    createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 4); //Fall
                    UpdateSemesterCreditsLabel(4, e.getCredits());
                }
            }
            else //if (eyear == (y + 2))
            {
                if (!term.Equals("Spring")) continue; //Only spring of third year is visible
                createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 5);
                UpdateSemesterCreditsLabel(5, e.getCredits());
            }
        }
    } //end initializeElectiveBoxes()

    /// <summary>
    /// initializeSemesterLabels()
    /// Graphical View Function
    /// 
    /// Set semester labels to display the correct semester information.
    /// </summary>
    private void initializeSemesterLabels()
    {
        //Get currently visible years
        int y = Convert.ToInt32((String)Session["Advisor_templateYearGV"]);
        int y1 = y + 1;
        int y2 = y + 2;
        //Initialize labels
        SemesterLabel1.Text = "Fall " + y;
        SemesterLabel2.Text = "Spring " + y1;
        SemesterLabel3.Text = "Summer " + y1;
        SemesterLabel4.Text = "Fall " + y1;
        SemesterLabel5.Text = "Spring " + y2;
    } //end initializeSemesterLabels()

    /// <summary>
    /// initializeSemesterRegions()
    /// Graphical View Function
    /// 
    /// Create JavaScript code for initializing semester regions as drop targets.
    /// </summary>
    private void initializeSemesterRegions()
    {
        for (int i = 1; i <= 5; i++)
        {
            //Dynamic JavaScript - create code for each drop target
            JavaScriptPageLoad.Text += "var target" + i + " = new AdviseUP.UI.SemesterRegion($get('MainBox_SemesterRegion" + i + "'), '" + i + "'); ";
            JavaScriptPageLoad.Text += "target" + i + ".initialize(); ";
        }
    } //end initializeSemesterRegions()

    /// <summary>
    /// createCourseBox()
    /// Graphical View Function
    /// 
    /// Create an individual course box with ASP.NET web controls.
    /// Also, create JavaScript code for initializing the course box as a drag source.
    /// </summary>
    /// <param name="courseID">int courseID - the unique course ID in the database</param>
    /// <param name="deptNum">String deptNum - the department and number of the course (e.g. CS203)</param>
    /// <param name="courseName">String courseName - the name of the course</param>
    /// <param name="credits">double credits - the number of credits for the course</param>
    /// <param name="regionNumber">int regionNumber - the semester region that the course is currently located (1 through 5)</param>
    /// <param name="term">String term - the term that the course in currently scheduled for.</param>
    private void createCourseBox(String courseID, String deptNum, String courseName, double credits, int regionNumber, String term)
    {
        //Create each container and control, placing appropriate controls in the right container
        //Outer Panel (Container, White, Non-Draggable)
        Panel p = new Panel();
        p.CssClass = "courseCSS";
        //Inner Panel (Container, Blue, Draggable, inside Outer Panel)
        Panel cb = new Panel();
        cb.ID = "CourseBoxc$" + courseID;
        cb.CssClass = "courseLabelCSS";
        //Course Name Text (inside Inner Panel)
        Literal lit = new Literal();
        lit.Text = "<span style=\"font-size:12px;\">" + deptNum + " (" + credits + ")" + "</span><br />";
        lit.Text += "<span>" + courseName + "</span>";
        //Manage Course Button (inside Outer Panel)
        Button bb1 = new Button();
        bb1.Text = "Manage";
        bb1.ID = "mnc" + courseID;
        bb1.CssClass = "courseButtonCSS";
        bb1.Click += new EventHandler(ManageCourseButtonGV_Click);
        Button bb2 = new Button();
        bb2.Text = "Remove";
        bb2.ID = "rmc" + courseID;
        bb2.CssClass = "courseButtonCSS";
        bb2.OnClientClick = "javascript:return confirm('Are you sure you want to remove this course?');";
        bb2.Click += new EventHandler(RemoveCourseButtonGV_Click);
        //Add controls to Inner Panel
        cb.Controls.Add(lit);
        //Add controls to Outer Panel
        p.Controls.Add(cb);
        p.Controls.Add(new LiteralControl("<center>"));
        p.Controls.Add(bb1);
        p.Controls.Add(new LiteralControl("&nbsp;"));
        p.Controls.Add(bb2);
        p.Controls.Add(new LiteralControl("</center>"));

        //Add course to correct semester region
        switch (regionNumber)
        {
            case 1:
                SemesterRegion1.Controls.Add(p);
                SemesterRegion1.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 2:
                SemesterRegion2.Controls.Add(p);
                SemesterRegion2.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 3:
                SemesterRegion3.Controls.Add(p);
                SemesterRegion3.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 4:
                SemesterRegion4.Controls.Add(p);
                SemesterRegion4.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 5:
            default:
                SemesterRegion5.Controls.Add(p);
                SemesterRegion5.Controls.Add(new LiteralControl("<br /><br />"));
                break;
        }

        //Dynamic JavaScript - create code for drag source
        JavaScriptPageLoad.Text += "var sourceC" + courseID + " = new AdviseUP.UI.CourseBox($get('MainBox_CourseBoxc$" + courseID + "'), 'c" + courseID + "'); ";
        JavaScriptPageLoad.Text += "sourceC" + courseID + ".initialize();";
    } //end createCourseBox()

    /// <summary>
    /// createElectiveBox()
    /// Graphical View Function
    /// 
    /// Create an individual elective box with ASP.NET web controls.
    /// Also, create JavaScript code for initializing the elective box as a drag source.
    /// </summary>
    /// <param name="electiveID">int electiveID - the unique database ID of the elective</param>
    /// <param name="electiveName">String electiveName - the name of the elective</param>
    /// <param name="term">String term - the current term of the elective</param>
    /// <param name="credits">double credits - the number of credits that the selected course is worth</param>
    /// <param name="choiceList">Dictionary(int, Course) choiceList - the list of elective choices</param>
    /// <param name="selectedCourseID">int selectedCourseID - the unique database ID of the currently selected course</param>
    /// <param name="regionNumber">int regionNumber - the semester region that the course is currently located (1 through 5)</param>
    private void createElectiveBox(int electiveID, String electiveName, String term, double credits, Dictionary<String, Course> choiceList, String selectedCourseID, int regionNumber)
    {
        //Create each container and control, placing appropriate controls in the right container
        //Outer Panel (Container, White, Non-Draggable)
        Panel p = new Panel();
        p.CssClass = "electiveCSS";
        //Inner Panel (Container, Blue, Draggable, inside Outer Panel)
        Panel eb = new Panel();
        eb.ID = "CourseBoxe" + electiveID + "$" + selectedCourseID;
        eb.CssClass = "courseLabelCSS";
        //Elective Name Text (inside Inner Panel)
        Literal lit = new Literal();
        lit.Text = "<span style=\"font-size:12px;\">Elective: " + electiveName + " (" + credits + ")" + "</span><br />";
        //Elective Choices Dropdown (inside Outer Panel)
        DropDownList db = new DropDownList();
        db.ID = electiveID + "%" + term + "%" + selectedCourseID;
        db.Width = new Unit("90%");
        db.AutoPostBack = true;
        db.SelectedIndexChanged += new EventHandler(chooseElectiveOption);
        db.Items.Add(new ListItem("Choose Option", "" + -1));
        String selectedName = "";
        foreach (String i in choiceList.Keys)
        {
            Course c = choiceList[i];
            String name = c.getDpt() + c.getNum() + ": " + c.getName();
            db.Items.Add(new ListItem(name, "" + i));
            if (selectedCourseID == i)
            {
                selectedName = name;
            }
        }
        //Selected Course Name Text (inside Inner Panel)
        lit.Text += "<span>" + selectedName + "</span>";
        //Elective Info Button (inside Outer Panel)
        Button bb1 = new Button();
        bb1.Text = "Manage";
        bb1.ID = "mne" + selectedCourseID + "%" + electiveID;
        bb1.CssClass = "courseButtonCSS";
        bb1.Click += new EventHandler(ManageCourseButtonGV_Click);
        Button bb2 = new Button();
        bb2.Text = "Remove";
        bb2.ID = "rme%" + selectedCourseID + "%" + electiveID;
        bb2.CssClass = "courseButtonCSS";
        bb2.OnClientClick = "javascript:return confirm('Are you sure you want to remove this elective?')";
        bb2.Click += new EventHandler(RemoveCourseButtonGV_Click);
        //Add controls to Inner Panel
        eb.Controls.Add(lit);
        //Add controls to Outer Panel
        p.Controls.Add(eb);
        p.Controls.Add(db);
        p.Controls.Add(new LiteralControl("<br /><center>"));
        p.Controls.Add(bb1);
        p.Controls.Add(new LiteralControl("&nbsp;"));
        p.Controls.Add(bb2);
        p.Controls.Add(new LiteralControl("</center>"));

        //Add elective to correct semester region
        switch (regionNumber)
        {
            case 1:
                SemesterRegion1.Controls.Add(p);
                SemesterRegion1.Controls.Add(new LiteralControl("<br />"));
                break;
            case 2:
                SemesterRegion2.Controls.Add(p);
                SemesterRegion2.Controls.Add(new LiteralControl("<br />"));
                break;
            case 3:
                SemesterRegion3.Controls.Add(p);
                SemesterRegion3.Controls.Add(new LiteralControl("<br />"));
                break;
            case 4:
                SemesterRegion4.Controls.Add(p);
                SemesterRegion4.Controls.Add(new LiteralControl("<br />"));
                break;
            case 5:
            default:
                SemesterRegion5.Controls.Add(p);
                SemesterRegion5.Controls.Add(new LiteralControl("<br />"));
                break;
        }

        //Dynamic JavaScript - create code for drag source
        JavaScriptPageLoad.Text += "var sourceE" + electiveID + selectedCourseID + " = new AdviseUP.UI.CourseBox($get('MainBox_CourseBoxe" + electiveID + "$" + selectedCourseID + "'), 'e" + electiveID + "s" + selectedCourseID + "'); ";
        JavaScriptPageLoad.Text += "sourceE" + electiveID + selectedCourseID + ".initialize();";
    } //end createElectiveBox()
    protected void chooseElectiveOption(object sender, EventArgs e)
    {
        DropDownList db = sender as DropDownList;
        String templateID = (String)Session["Advisor_templateID"];
        String[] electiveIDAndTerm = db.ID.Split('%');
        if (StoredProcedures.updateElectiveSelectedCourseInTemplate(templateID, electiveIDAndTerm[0], electiveIDAndTerm[2], "" + db.SelectedItem.Value) == StoredProcedures.FAILURE)
        {
            MessageBox.Show("The course you are trying to select for this elective is currently chosen for a different instance of this elective.");
        }
        initializeJavaScript();
    }
    protected void ManageCourseButtonGV_Click(object sender, EventArgs e)
    {
        Button bb = sender as Button;
        String cid = bb.ID;
        String templateID = (String)Session["Advisor_templateID"];
        if (cid[2] == 'c')
        {
            Response.Redirect("~/Advisor/ManageCourse.aspx?cid=" + cid.Substring(3) + "&return=t" + templateID);
        }
        else if (cid[2] == 'e')
        {
            cid = cid.Substring(cid.IndexOf("%") + 1);
            //get the page setup for the create elective view
            CreateElective_Click(sender, e);
            //get current elective's name and choices to populate lists
            Dictionary<String, object> result = StoredProcedures.getElectiveName(cid);
            ElectiveName.Text = (String)result["name"];
            ElectiveCourseList.Items.Clear();
            List<Dictionary<String, object>> choices = StoredProcedures.getElectiveChoices(cid);
            foreach (Dictionary<String, object> i in choices)
            {
                ElectiveCourseList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
            }
            //set the electivemanagelabel to the electiveID so the elective is edited and not recreated
            ElectiveManageLabel.Text = cid;

        }
    }
    protected void RemoveCourseButtonGV_Click(object sender, EventArgs e)
    {
        Button bb = sender as Button;
        String cid = bb.ID;
        String templateID = (String)Session["Advisor_templateID"];
        if (cid[2] == 'c')
        {
            StoredProcedures.removeCourseFromTemplate(templateID, cid.Substring(3));
        }
        else if (cid[2] == 'e')
        {
            String[] electiveAndCourseID = cid.Split('%');
            StoredProcedures.removeElectiveFromTemplate(templateID, electiveAndCourseID[2], electiveAndCourseID[1]);
        }
        initializeJavaScript();
    }
    protected void ListInfoButton_Click(object sender, EventArgs e)
    {
        Button bb = sender as Button;
        String id = bb.ID.Substring(10);
        Response.Redirect("~/Advisee/CourseInfo.aspx?cid=" + id);
    }
    protected void LeftButton_Click(object sender, EventArgs e)
    {
        int year = Convert.ToInt32((String)Session["Advisor_templateYearGV"]);
        int minYear = 1;
        if (year > minYear) year = year - 1;
        Session["Advisor_templateYearGV"] = "" + year;
        initializeJavaScript();
    }
    protected void RightButton_Click(object sender, EventArgs e)
    {
        int year = Convert.ToInt32((String)Session["Advisor_templateYearGV"]);
        int maxYear = 8;
        if (year < maxYear) year = year + 1;
        Session["Advisor_templateYearGV"] = "" + year;
        initializeJavaScript();
    }

    [WebMethod]
    public static void MoveCourse(String crn, String sem)
    {
        int semester = Convert.ToInt32(sem);
        int y = Convert.ToInt32((String)HttpContext.Current.Session["Advisor_templateYearGV"]);
        int y1 = y + 1;
        int y2 = y + 2;
        String templateID = (String)HttpContext.Current.Session["Advisor_templateID"];
        String term = "";
        switch (semester)
        {
            case 1:
                term = SharedFunctions.convertToTermCode("" + y, "Fall");
                break;
            case 2:
                term = SharedFunctions.convertToTermCode("" + y1, "Spring");
                break;
            case 3:
                term = SharedFunctions.convertToTermCode("" + y1, "Summer");
                break;
            case 4:
                term = SharedFunctions.convertToTermCode("" + y1, "Fall");
                break;
            case 5:
            default:
                term = SharedFunctions.convertToTermCode("" + y2, "Spring");
                break;
        }
        int numZeros = 6 - term.Length;
        for (int i = 0; i < numZeros; i++)
        {
            term = "0" + term;
        }
        String courseID = "";
        String selectedCourseID = "";
        if (crn[0] == 'c')
        {
            courseID = crn.Substring(1);
            StoredProcedures.updateCourseInTemplate(templateID, courseID, term);
        }
        else
        {
            int sloc = crn.IndexOf('s');
            selectedCourseID = crn.Substring(sloc + 1);
            courseID = crn.Substring(1, (sloc - 1));
            StoredProcedures.updateElectiveTermInTemplate(templateID, courseID, selectedCourseID, term);
        }
    }

    /// <summary>
    /// UpdateSemesterCreditsLabel()
    /// Graphical View Function
    /// 
    /// Updates the label listing how many credits being taken in a semester.
    /// </summary>
    /// <param name="sem">int sem - the semester to update</param>
    /// <param name="credits">int creditsToAdd - the number of credits to add to the running total</param>
    private void UpdateSemesterCreditsLabel(int sem, double creditsToAdd)
    {
        int space = 0;
        double creditsSoFar = 0;
        switch (sem)
        {
            case 1:
                space = SemesterCreditsLabel1.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel1.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel1.Text = "Credits: " + creditsSoFar;
                break;
            case 2:
                space = SemesterCreditsLabel2.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel2.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel2.Text = "Credits: " + creditsSoFar;
                break;
            case 3:
                space = SemesterCreditsLabel3.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel3.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel3.Text = "Credits: " + creditsSoFar;
                break;
            case 4:
                space = SemesterCreditsLabel4.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel4.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel4.Text = "Credits: " + creditsSoFar;
                break;
            case 5:
            default:
                space = SemesterCreditsLabel5.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel5.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel5.Text = "Credits: " + creditsSoFar;
                break;
        }
    } //end UpdateSemesterCreditsLabel()
    
    // setEverything
    //
    // A helper method that sets the boolean values for several functions at once!
    //
    // @param addCourse the bool for setAddCourseView
    // @param addElec the bool for setAddElectiveView
    // @param graphic the bool for setGraphicalView
    // @param list the bool for setListView
    // @param createElec the bool for setCreateElectiveView
    // @param chooseTemplate the bool for setChooseTemplateView
    // @param page1 the first bool for setPageControls
    // @param page2 the second bool for setPageControls
    // @param page3 the third bool for setPageControls
    //
    private void setEverything(bool addCourse, bool addElec, bool graphic, bool list, bool createElec, bool chooseTemplate, bool page1, bool page2, bool page3)
    {
        setAddCourseView(addCourse);
        setAddElectiveView(addElec);
        setGraphicalView(graphic);
        setListView(list);

        //Functions being added (Feb 2013)
        setCreateElectiveView(createElec);
        setChooseTemplateView(chooseTemplate);
        setPageControls(page1, page2, page3);
    }
}